﻿using Common.Communal;
using MediatR;
using Product.API.ISerivces.Upload;
using Product.API.Serivces.Upload;
using Product.API.Write.Applications.Commands.Upload;

namespace Product.API.Write.Applications.CommandHandlers.Upload
{
    /// <summary>
    /// 文件删除命令处理
    /// </summary>
    public class DeleteFileCommandHandler : IRequestHandler<DeleteFileCommand, ApiResult<int>>
    {
        /// <summary>
        /// 文件服务
        /// </summary>
        private readonly IUploadSerivces uploadSerivces;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="uploadSerivces">文件服务</param>
        public DeleteFileCommandHandler(IUploadSerivces uploadSerivces)
        {
            this.uploadSerivces = uploadSerivces;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public Task<ApiResult<int>> Handle(DeleteFileCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code = EnumCode.Ok;
            result.Message = EnumCode.Ok.ToString();

            try
            {
                int data = uploadSerivces.DeleteFile(request.url);
                if (data == 0)
                {
                    throw new Exception("删除失败");
                }
                result.Data = data;

                return Task.FromResult(result);
            }
            catch (Exception ex)
            {
                result.Code = EnumCode.Fail;
                result.Message = EnumCode.Fail.ToString();
                return Task.FromResult(result);
            }

        }
    }
}
